package com.ugoodtech.mdcc.client.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.ResponseObject.PersonKpiResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.dto.LabelValue;
import com.ugoodtech.mdcc.client.service.WeekServiceReportService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.CoreWeekServiceReportService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.*;

@Api(description = "技术人员kpi")
@RestController
@RequestMapping("/weekServiceReport")
public class WeekServiceReportServiceController {

    @Autowired
    private WeekServiceReportService weekServiceReportService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ModuleAuthorityRepository moduleAuthorityRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private CoreWeekServiceReportService coreWeekServiceReportService;

    @ApiOperation("获得技术人员kpi报告")
    @RequestMapping(value = "getWeekReport", method = RequestMethod.GET)
    public com.ugoodtech.mdcc.core.dto.JsonResponse getWeekReport(Principal principal,
                                                                  @ApiParam("省份多选") @RequestParam(value = "province", required = false) String province,
                                                                  @ApiParam("品牌") @RequestParam(value = "brand", required = false) String brand,
                                                                  @ApiParam("维修站类型") @RequestParam(value = "category", required = false) String category,
                                                                  @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName,
                                                                  @ApiParam("服务开始时间") @RequestParam(value = "serviceStartTime", required = false) Long serviceStartTime,
                                                                  @ApiParam("服务结束时间") @RequestParam(value = "serviceEndTime", required = false) Long serviceEndTime,
                                                                  @ApiParam("开始时间") @RequestParam(value = "startTime", required = false) Long startTime,
                                                                  @ApiParam("结束时间") @RequestParam(value = "endTime", required = false) Long endTime,
                                                                  @ApiParam("服务项目") @RequestParam(value = "serviceType", required = false) String serviceType,
                                                                  @ApiParam("所属部门") @RequestParam(value = "department", required = false) String department,
                                                                  @ApiParam("服务次数") @RequestParam(value = "serviceNum", required = false) Integer serviceNum,
                                                                  @ApiParam("技术人员姓名") @RequestParam(value = "userName", required = false) String userName,
                                                                  @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                                                  @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) String customerStat,
                                                                  @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) String customerType,
                                                                  @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String paintBrand,
                                                                  @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition,
                                                                  @ApiParam("常规服务报告状态") @RequestParam(value = "reportStatus", required = false) String reportStatus,
                                                                  @ApiParam("需跟进报告处理状态") @RequestParam(value = "serviceReportStatus", required = false) String serviceReportStatus,
                                                                  @ApiParam("是否填写满意度：true:填写，false:未填写") @RequestParam(value = "type", required = false) Boolean type,
                                                                  @ApiParam("满意度打分") @RequestParam(value = "score", required = false) String score,
                                                                  @ApiParam("是否填写精益钣喷：true:填写，false:未填写") @RequestParam(value = "paintType", required = false) Boolean paintType,
                                                                  @ApiParam("该维修站是否使用我司增值服务") @RequestParam(value = "payService", required = false) String payService,
                                                                  @ApiParam("油漆配送时效") @RequestParam(value = "sentTime", required = false) String sentTime,
                                                                  @ApiParam("经销商上门服务周期") @RequestParam(value = "serviceTime", required = false) String serviceTime,
                                                                  @ApiParam(value = "维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum

    ) {
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return com.ugoodtech.mdcc.core.dto.JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
//        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.REPORT_STATISTICS_WECHAT);
//        boolean b = clientUser.getAuthorities().contains(m);
//        if (b == false) {
//            return JsonResponse.errorResponseWithError("抱歉", "您没有此权限:您没有此权限:报告统计（微信端）");
//        }
        return coreWeekServiceReportService.statWeekReport(clientUser,province, brand, category,
                stationName, serviceStartTime, serviceEndTime, startTime, endTime, serviceType, department,
                serviceNum, userName, city,customerStat, customerType,paintBrand, productPosition, reportStatus,
                serviceReportStatus, type, score, paintType, payService, sentTime, serviceTime, stationNum);
    }

    @ApiOperation("获得技术人员kpi报告--改")
    @RequestMapping(value = "getPersonKpiReport", method = RequestMethod.GET)
    public JsonResponse getPersonKpiReport(Principal principal,
                                           @ApiParam("技术人员ID") @RequestParam(value = "userId") Long userId,
                                           @ApiParam("维修站ID") @RequestParam(value = "stationId", required = false) Long stationId) {
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.REPORT_STATISTICS_WECHAT);
        boolean b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            return JsonResponse.errorResponseWithError("抱歉", "您没有此权限:您没有此权限:报告统计（微信端）");
        }
        return null;
    }

    @ApiOperation("模糊搜索维修站")
    @RequestMapping(value = "/findOneStation", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse findOneStation(@ApiParam("省份") @RequestParam(value = "province") String province,
                                       @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                       @ApiParam("维修站名称") @RequestParam(value = "userName", required = false) String stationName) {
        QStation qStation = QStation.station;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStation.deleted.eq(false));
        builder.and(qStation.enabled.eq(true));
        builder.and(qStation.checkStation.eq(true));
        builder.and(qStation.user.isNotNull());
        builder.and(qStation.province.isNotNull());
        builder.and(qStation.city.isNotNull());
        builder.and(qStation.contact.isNotNull());
        if (StringUtils.isNotEmpty(city)) {
            builder.and(qStation.city.eq(city));
        }
        builder.and(qStation.province.eq(province));
        builder.and(qStation.name.like("%" + stationName + "%"));
        List<Station> stationList = (List<Station>) stationRepository.findAll(builder);
        List<LabelValue> labelValues = new ArrayList<>();
        if (null != stationList) {
            labelValues = toStationLableValue(stationList);
        }
        return JsonResponse.successResponseWithData(labelValues);
    }

    private List<LabelValue> toStationLableValue(List<Station> stationList) {
        List<LabelValue> labelValues = new ArrayList<>();
        for (Station station : stationList) {
            LabelValue labelValue = new LabelValue(station.getName(), station.getId() + "");
            labelValues.add(labelValue);
        }
        return labelValues;
    }


    @ApiOperation("模糊搜索用户")
    @RequestMapping(value = "/findOneUser", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse findOneUser(Principal principal,
                                    @ApiParam("省份") @RequestParam(value = "province", required = false) String province,
                                    @ApiParam("用户名名称") @RequestParam(value = "userName", required = false) String userName) {
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
//        if (StringUtils.isEmpty(province) && StringUtils.isEmpty(userName)) {
//            return JsonResponse.successResponseWithData(new Object[0]);
//        }
//        UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
//        List<Nation> nationList = userProfile.getNationList();
//        List<String> nationStr = new ArrayList<>();
//        if (nationList != null && nationList.size() > 0) {
//            for (Nation nation : nationList) {
//                nationStr.add(nation.getProvince());
//            }
//        }
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        if (StringUtils.isNotEmpty(userName)) {
            builder.and(qUserProfile.realName.like("%" + userName + "%"));
        }
//        if (StringUtils.isEmpty(province) && StringUtils.isNotEmpty(userName) && nationStr.size() > 0) {
//            builder.and(qUserProfile.nationList.any().province.in(nationStr));
//        }
//        if (StringUtils.isNotEmpty(province)) {
//            builder.and(qUserProfile.nationList.any().province.eq(province));
//        }
        List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
        List<LabelValue> labelValues = new ArrayList<>();
        if (null != userProfileList) {
            labelValues = toLableValue(userProfileList);
        }
        return JsonResponse.successResponseWithData(labelValues);
    }

    private List<LabelValue> toLableValue(List<UserProfile> userProfileList) {
        List<LabelValue> labelValues = new ArrayList<>();
        for (UserProfile userProfile : userProfileList) {
            LabelValue labelValue = new LabelValue(userProfile.getRealName(), userProfile.getUser().getId() + "");
            labelValues.add(labelValue);
        }
        return labelValues;
    }


    @ApiOperation("技术人员KPI-维修站列表-主要查看维修站报告情况-3个值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "weekServiceKpiList", method = RequestMethod.GET)
    public JsonResponse weekServiceKpiList(Principal principal,
                                           Pageable pageable,
                                           @ApiParam("省份多选") @RequestParam(value = "provinces", required = false) String provinces,
                                           @ApiParam("品牌") @RequestParam(value = "brandname", required = false) String brandname,
                                           @ApiParam("维修站类型") @RequestParam(value = "category", required = false) String category,
                                           @ApiParam("服务开始时间") @RequestParam(value = "serviceStartTime", required = false) Long serviceStartTime,
                                           @ApiParam("服务结束时间") @RequestParam(value = "serviceEndTime", required = false) Long serviceEndTime,
                                           @ApiParam("技术人员名称") @RequestParam(value = "userName", required = false) String userName,
                                           @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        if (StringUtils.isNotEmpty(userName)) {
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
            List<Long> userIds = new ArrayList<>();
            for (UserProfile user : userProfileList) {
                userIds.add(user.getUser().getId());
            }
            builder.and(qStationReport.user.id.in(userIds));
        }
        if (serviceStartTime != null && serviceStartTime != 0 && serviceEndTime != null && serviceEndTime != 0) {
            builder.and(qStationReport.startServiceTime.after(new Date(serviceStartTime)));
            builder.and(qStationReport.endServiceTime.before(new Date(serviceEndTime)));
        }
        if (StringUtils.isNotEmpty(provinces)) {
            builder.and(qStationReport.station.province.eq(provinces));
        } else {
            List<Nation> nationList = userProfile.getNationList();
            List<String> nationStr = new ArrayList<>();
            for (Nation nation : nationList) {
                nationStr.add(nation.getProvince());
            }
            if (nationStr != null && nationStr.size() != 0) {
                builder.and(qStationReport.station.province.in(nationStr));
            }
        }
        if (StringUtils.isNotEmpty(brandname)) {
            builder.and(qStationReport.station.brand.like("%" + brandname + "%"));
        } else {
            List<Brand> brandList = userProfile.getBrandList();
            List<String> brandStr = new ArrayList<>();
            for (Brand b : brandList) {
                brandStr.add(b.getBrandName());
            }
            if (brandStr != null && brandStr.size() != 0) {
                BooleanBuilder orBuilder = new BooleanBuilder();
                QStationReport qReport = QStationReport.stationReport;
                orBuilder.and(qReport.deleted.eq(false));
                orBuilder.and(qReport.enabled.eq(true));
                orBuilder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
                for (String str : brandStr) {
                    orBuilder.or(qStationReport.station.brand.like("%" + str + "%"));
                }
                builder.and(orBuilder);
            }
        }
        if (StringUtils.isNotEmpty(category)) {
            builder.and(qStationReport.station.category.eq(category));
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStationReport.station.name.like("%" + stationName + "%"));
        }
        Page<StationReport> stationReportList = stationReportRepository.findAll(builder, pageable);
        Map<Long, String> stationIds = new HashMap<>();
        for (StationReport report : stationReportList) {
            stationIds.put(report.getStation().getId(), "");
        }
        List<PersonKpiResponse> personKpiResponseList = new ArrayList<>();
        for (Long key : stationIds.keySet()) {
            Station station = stationRepository.findOne(key);
            if (station == null) {
                continue;
            }

            qStationReport = QStationReport.stationReport;
            builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
            builder.and(qStationReport.station.id.eq(key));
            List<StationReport> stationReports = (List<StationReport>) stationReportRepository.findAll(builder);
            PersonKpiResponse personKpiResponse = new PersonKpiResponse(station);
            int[] index = new int[3];
            int complete = 0;
            int need_follow = 0;
            int plan = 0;
            for (StationReport stationReport : stationReports) {
                StationRegularServiceReport answer = stationRegularServiceReportRepository.selectAnswer(stationReport.getId(), 181L);
                if (answer != null) {
                    complete += 1;
                }
                answer = stationRegularServiceReportRepository.selectAnswer(stationReport.getId(), 181L);
                if ((answer != null && !answer.getAnswerId().equals("181")) && !answer.getAnswerId().equals("354") || answer == null) {
                    need_follow += 1;
                }
                answer = stationRegularServiceReportRepository.selectAnswer(stationReport.getId(), 354L);
                if (answer != null) {
                    plan += 1;
                }
            }
            index[0] = complete;
            index[1] = need_follow;
            index[2] = plan;
            personKpiResponse.setIndex(index);
            personKpiResponseList.add(personKpiResponse);
        }
        return JsonResponse.successResponseWithData(personKpiResponseList);
    }
}